package com.snack.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.snack.shop.common.BusinessException;
import com.snack.shop.common.OrderStatus;
import com.snack.shop.dto.CreateOrderParam;
import com.snack.shop.dto.ReorderItemDTO;
import com.snack.shop.entity.*;
import com.snack.shop.mapper.AddressMapper;
import com.snack.shop.mapper.ErrandOrderMapper;
import com.snack.shop.mapper.OrderItemMapper;
import com.snack.shop.mapper.OrderMapper;
import com.snack.shop.mapper.ProductMapper;
import com.snack.shop.service.FileManageService;
import com.snack.shop.service.OrderService;
import com.snack.shop.service.MessageService;
import com.snack.shop.service.MerchantMessageService;
import com.snack.shop.service.SystemConfigService;
import com.snack.shop.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 订单服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ProductMapper productMapper;
    private final AddressMapper addressMapper;
    private final ErrandOrderMapper errandOrderMapper;
    private final SystemConfigService systemConfigService;
    private final FileManageService fileManageService;
    private final ObjectMapper objectMapper;
    private final com.snack.shop.service.WxPayService wxPayService;
    private final MessageService messageService;
    private final MerchantMessageService merchantMessageService;
    private final UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Long userId, CreateOrderParam param) {
        // 1. 检查地址
        Address address = addressMapper.selectById(param.getAddressId());
        if (address == null || !address.getUserId().equals(userId)) {
            throw new BusinessException("收货地址不存在");
        }

        // 2. 计算订单金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (CreateOrderParam.OrderItemParam item : param.getItems()) {
            Product product = productMapper.selectById(item.getProductId());
            if (product == null || product.getStatus() == 0) {
                throw new BusinessException("商品不存在或已下架");
            }
            if (product.getStock() < item.getQuantity()) {
                throw new BusinessException("商品【" + product.getName() + "】库存不足");
            }
            
            BigDecimal subtotal = product.getPrice().multiply(new BigDecimal(item.getQuantity()));
            totalAmount = totalAmount.add(subtotal);
        }

        // 3. 获取配送费配置
        BigDecimal deliveryFee = systemConfigService.getConfigValueAsDecimal("delivery_fee", BigDecimal.ZERO);
        BigDecimal actualAmount = totalAmount.add(deliveryFee);
        
        // 4. 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setOrderType(param.getOrderType());
        order.setStatus(0); // 待支付
        order.setTotalAmount(totalAmount);
        order.setDeliveryFee(deliveryFee);
        order.setActualAmount(actualAmount);
        order.setAddressId(address.getId());
        order.setDeliveryAddress(buildAddressText(address));
        order.setRemark(param.getRemark());
        
        orderMapper.insert(order);

        // 5. 创建订单明细
        for (CreateOrderParam.OrderItemParam item : param.getItems()) {
            Product product = productMapper.selectById(item.getProductId());
            
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getImage());
            orderItem.setPrice(product.getPrice());
            orderItem.setQuantity(item.getQuantity());
            orderItem.setSubtotal(product.getPrice().multiply(new BigDecimal(item.getQuantity())));
            
            orderItemMapper.insert(orderItem);
        }

        return order;
    }

    @Override
    public Page<Order> pageByUser(Long userId, Integer status, Integer orderType, Integer current, Integer size, String keyword) {
        Page<Order> page = new Page<>(current, size);

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);

        if (status != null) {
            wrapper.eq(Order::getStatus, status);
        }

        if (orderType != null) {
            wrapper.eq(Order::getOrderType, orderType);
        }

        if (keyword != null && !keyword.trim().isEmpty()) {
            String kw = keyword.trim();
            wrapper.and(w -> w.like(Order::getOrderNo, kw)
                               .or()
                               .like(Order::getDeliveryAddress, kw)
                               .or()
                               .like(Order::getRemark, kw)
                               .or()
                               .apply("exists (select 1 from t_order_item oi where oi.order_id = t_order.id and oi.product_name like {0})", "%" + kw + "%"));
        }

        wrapper.orderByDesc(Order::getCreateTime);

        Page<Order> result = orderMapper.selectPage(page, wrapper);
        // 为零食订单填充前3条商品项供前端简要展示
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            for (Order o : result.getRecords()) {
                if (o.getOrderType() != null && o.getOrderType() == 1) {
                    List<OrderItem> briefItems = orderItemMapper.selectList(
                        new LambdaQueryWrapper<OrderItem>()
                            .eq(OrderItem::getOrderId, o.getId())
                            .last("limit 3")
                    );
                    o.setItems(briefItems);
                }
            }
        }
        return result;
    }

    @Override
    public Page<Order> pageAll(Integer status, Integer orderType, Integer current, Integer size, String keyword) {
        Page<Order> page = new Page<>(current, size);
        
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        
        if (status != null) {
            wrapper.eq(Order::getStatus, status);
        }
        
        if (orderType != null) {
            wrapper.eq(Order::getOrderType, orderType);
        }
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            String kw = keyword.trim();
            wrapper.and(w -> w.like(Order::getOrderNo, kw)
                               .or()
                               .like(Order::getDeliveryAddress, kw)
                               .or()
                               .like(Order::getRemark, kw));
        }
        
        wrapper.orderByDesc(Order::getCreateTime);
        
        Page<Order> result = orderMapper.selectPage(page, wrapper);
        
        // 填充联系人信息（来自地址表）
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            for (Order order : result.getRecords()) {
                if (order.getAddressId() != null) {
                    Address address = addressMapper.selectById(order.getAddressId());
                    if (address != null) {
                        order.setContactName(address.getContactName());
                        order.setContactPhone(address.getContactPhone());
                    }
                }
                // 为零食订单填充前3条商品项供前端简要展示
                if (order.getOrderType() != null && order.getOrderType() == 1) {
                    List<OrderItem> briefItems = orderItemMapper.selectList(
                        new LambdaQueryWrapper<OrderItem>()
                            .eq(OrderItem::getOrderId, order.getId())
                            .last("limit 3")
                    );
                    order.setItems(briefItems);
                }
            }
        }
        
        return result;
    }

    @Override
    public Order getDetail(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 填充订单商品明细
        List<OrderItem> items = orderItemMapper.selectList(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId)
        );
        order.setItems(items);

        // 填充联系人信息（来自地址表）
        if (order.getAddressId() != null) {
            Address address = addressMapper.selectById(order.getAddressId());
            if (address != null) {
                order.setContactName(address.getContactName());
                order.setContactPhone(address.getContactPhone());
            }
        }

        return order;
    }

    // 旧的余额支付方法（已废弃，现在只支持微信支付）
    // 微信支付流程：
    // 1. 前端调用 PaymentController.createWxPayOrder() 创建预支付订单
    // 2. 用户完成微信支付
    // 3. 微信回调 PaymentController.wxPayNotify()
    // 4. 调用 handlePaySuccess() 更新订单状态和扣减库存
    // @Override
    // @Transactional(rollbackFor = Exception.class)
    // public void pay(Long userId, Long orderId) {
    //     Order order = orderMapper.selectById(orderId);
    //     if (order == null || !order.getUserId().equals(userId)) {
    //         throw new BusinessException("订单不存在");
    //     }
    //     if (order.getStatus() != 0) {
    //         throw new BusinessException("订单状态异常");
    //     }
    //
    //     // 模拟支付成功
    //
    //     // 更新订单状态
    //     order.setStatus(1); // 待接单
    //     order.setPayTime(LocalDateTime.now());
    //     orderMapper.updateById(order);
    //
    //     // 判断订单类型，处理不同业务逻辑
    //     Integer orderType = order.getOrderType();
    //     
    //     // orderType: 1-零食订单, 2-取快递, 3-取外卖, 4-代取奶咖
    //     if (orderType != null && orderType == 1) {
    //         // 零食订单：扣减库存
    //         handleSnackOrderPay(orderId);
    //     } else if (orderType != null && (orderType == 2 || orderType == 3 || orderType == 4)) {
    //         // 代取订单：确认图片
    //         handleErrandOrderPay(orderId);
    //     }
    // }
    
    /**
     * 处理零食订单支付
     */
    private void handleSnackOrderPay(Long orderId) {
        List<OrderItem> items = orderItemMapper.selectList(
            new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderId)
        );
        
        for (OrderItem item : items) {
            Product product = productMapper.selectById(item.getProductId());
            if (product != null) {
                product.setStock(product.getStock() - item.getQuantity());
                product.setSales(product.getSales() + item.getQuantity());
                productMapper.updateById(product);
            }
        }
    }
    
    /**
     * 处理代取订单支付 - 确认订单创建时上传的图片
     */
    private void handleErrandOrderPay(Long orderId) {
        try {
            List<String> imageUrls = new ArrayList<>();
            
            // 获取跑腿订单详情
            ErrandOrder errandOrder = errandOrderMapper.selectOne(
                new LambdaQueryWrapper<ErrandOrder>().eq(ErrandOrder::getOrderId, orderId)
            );
            
            if (errandOrder != null) {
                // 收集第一张图片（快递单号截图/订单截图）
                if (errandOrder.getFirstImage() != null) {
                    imageUrls.addAll(parseImageUrls(errandOrder.getFirstImage()));
                }
                
                // 收集第二张图片（身份码截图/取餐码截图）
                if (errandOrder.getSecondImage() != null) {
                    imageUrls.addAll(parseImageUrls(errandOrder.getSecondImage()));
                }
            }
            
            // 确认所有图片
            if (!imageUrls.isEmpty()) {
                fileManageService.confirmFiles(imageUrls, "order", orderId);
                log.info("支付成功，确认订单图片为正式状态: orderId={}, imageCount={}", orderId, imageUrls.size());
            }
        } catch (Exception e) {
            log.error("确认订单图片失败: orderId={}", orderId, e);
            // 不影响主流程
        }
    }
    
    /**
     * 解析图片URL（支持JSON数组格式和逗号分隔格式）
     */
    private List<String> parseImageUrls(String imagesStr) {
        if (imagesStr == null || imagesStr.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            // 尝试解析JSON数组格式：["url1", "url2"]
            List<String> urls = objectMapper.readValue(imagesStr, new TypeReference<List<String>>() {});
            return urls.stream()
                    .filter(url -> url != null && !url.trim().isEmpty())
                    .collect(Collectors.toList());
        } catch (Exception e) {
            // 兼容逗号分隔格式：url1,url2
            List<String> urls = new ArrayList<>();
            for (String url : imagesStr.split(",")) {
                String trimmed = url.trim();
                if (!trimmed.isEmpty()) {
                    urls.add(trimmed);
                }
            }
            return urls;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(Long userId, Long orderId, String reason) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在");
        }
        
        // 只有待支付和待接单状态可以直接取消
        if (order.getStatus() != OrderStatus.WAIT_PAY && order.getStatus() != OrderStatus.WAIT_ACCEPT) {
            throw new BusinessException("订单状态不允许取消");
        }

        // 判断是否已支付
        boolean isPaid = (order.getStatus() >= OrderStatus.WAIT_ACCEPT && order.getStatus() <= OrderStatus.DELIVERED); // 待接单、配送中等状态说明已支付
        
        // 如果已支付，需要退款并恢复库存
        if (isPaid) {
            log.info("用户取消订单，开始退款：orderId={}, orderNo={}, amount={}", 
                    orderId, order.getOrderNo(), order.getActualAmount());
            
            try {
                // 调用微信支付退款接口（仅支持微信支付）
                if (order.getPayType() != null && order.getPayType() == 2 && order.getTransactionId() != null) {
                    // 微信支付退款
                    String refundNo = wxPayService.refund(order, reason != null ? reason : "用户取消订单");
                    log.info("微信退款申请成功：orderId={}, refundNo={}", orderId, refundNo);
                }
                // 余额支付功能已废弃
                // else if (order.getPayType() != null && order.getPayType() == 1) {
                //     // 余额支付，直接退回余额
                //     log.info("余额退款：orderId={}, amount={}", orderId, order.getActualAmount());
                // }
                
                // 恢复库存和销量（仅零食订单）
                if (order.getOrderType() == 1) {
                    List<OrderItem> items = orderItemMapper.selectList(
                        new LambdaQueryWrapper<OrderItem>()
                            .eq(OrderItem::getOrderId, orderId)
                    );
                    
                    for (OrderItem item : items) {
                        Product product = productMapper.selectById(item.getProductId());
                        if (product != null) {
                            product.setStock(product.getStock() + item.getQuantity());
                            product.setSales(product.getSales() - item.getQuantity());
                            productMapper.updateById(product);
                            log.info("恢复商品库存：productId={}, quantity={}", 
                                    item.getProductId(), item.getQuantity());
                        }
                    }
                }
                
                // 已支付后取消，状态为"已退款"
                order.setStatus(OrderStatus.REFUNDED);
                
            } catch (Exception e) {
                log.error("退款失败：orderId={}", orderId, e);
                throw new BusinessException("退款失败：" + e.getMessage());
            }
        } else {
            // 未支付取消，状态为"已取消"
            order.setStatus(OrderStatus.CANCELLED);
        }
        
        order.setCancelReason(reason);
        order.setCancelTime(LocalDateTime.now());
        orderMapper.updateById(order);
        if (isPaid) {
            messageService.create(order.getUserId(), 1, "订单已退款", "订单" + order.getOrderNo() + "已退款", "order", order.getId());
            // 为商家创建消息：订单已取消并退款（仅零食订单）
            if (order.getOrderType() != null && order.getOrderType() == 1) {
                try {
                    Long merchantId = getMerchantId();
                    if (merchantId != null) {
                        merchantMessageService.create(merchantId, 1, "订单已取消", "订单" + order.getOrderNo() + "已取消并退款，金额¥" + order.getActualAmount(), "order", order.getId());
                    }
                } catch (Exception e) {
                    log.warn("创建商家消息失败, orderId={}", orderId, e);
                }
            }
        } else {
            messageService.create(order.getUserId(), 1, "订单已取消", "订单" + order.getOrderNo() + "已取消", "order", order.getId());
            // 为商家创建消息：订单已取消（仅零食订单）
            if (order.getOrderType() != null && order.getOrderType() == 1) {
                try {
                    Long merchantId = getMerchantId();
                    if (merchantId != null) {
                        merchantMessageService.create(merchantId, 1, "订单已取消", "订单" + order.getOrderNo() + "已取消（未支付）", "order", order.getId());
                    }
                } catch (Exception e) {
                    log.warn("创建商家消息失败, orderId={}", orderId, e);
                }
            }
        }
        
        log.info("订单取消成功：orderId={}, status={}, isPaid={}", orderId, order.getStatus(), isPaid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceive(Long userId, Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || !order.getUserId().equals(userId)) {
            throw new BusinessException("订单不存在");
        }
        if (order.getStatus() != OrderStatus.DELIVERING) {
            throw new BusinessException("订单状态错误，无法确认收货");
        }

        // 更新订单状态为已完成（统一状态v2.0：零食订单确认收货后直接完成状态6）
        order.setStatus(6);
        order.setConfirmTime(LocalDateTime.now());
        order.setFinishTime(LocalDateTime.now());
        orderMapper.updateById(order);
        messageService.create(order.getUserId(), 1, "确认收货成功", "订单" + order.getOrderNo() + "已完成", "order", order.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void acceptOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != 1) {
            throw new BusinessException("订单状态错误，无法接单");
        }
        
        // 更新订单状态为配送中（统一状态v2.0：零食订单接单后直接进入配送中状态3）
        order.setStatus(3);
        order.setAcceptTime(LocalDateTime.now());
        orderMapper.updateById(order);
        messageService.create(order.getUserId(), 1, "商家已接单", "订单" + order.getOrderNo() + "商家已接单，开始配送", "order", order.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectOrder(Long orderId, String reason) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != 1) {
            throw new BusinessException("订单状态错误，无法拒单");
        }
        
        log.info("商家拒单，开始退款：orderId={}, orderNo={}, amount={}", 
                orderId, order.getOrderNo(), order.getActualAmount());
        
        try {
            // 调用微信支付退款接口（仅支持微信支付）
            if (order.getPayType() != null && order.getPayType() == 2 && order.getTransactionId() != null) {
                // 微信支付退款
                String refundNo = wxPayService.refund(order, reason != null ? reason : "商家拒单");
                log.info("微信退款申请成功：orderId={}, refundNo={}", orderId, refundNo);
            }
            // 余额支付功能已废弃
            // else if (order.getPayType() != null && order.getPayType() == 1) {
            //     // 余额支付，直接退回余额
            //     log.info("余额退款：orderId={}, amount={}", orderId, order.getActualAmount());
            // }
            
            // 商家拒单 = 已支付后退款，状态应该是"已退款"
            order.setStatus(8); // 已退款
            order.setCancelReason(reason != null ? reason : "商家拒单");
            order.setCancelTime(LocalDateTime.now());
            orderMapper.updateById(order);
            messageService.create(order.getUserId(), 1, "商家拒单并退款", "订单" + order.getOrderNo() + "已退款", "order", order.getId());
            
            // 恢复库存和销量（仅零食订单）
            if (order.getOrderType() == 1) {
                List<OrderItem> items = orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderId, orderId)
                );
                
                for (OrderItem item : items) {
                    Product product = productMapper.selectById(item.getProductId());
                    if (product != null) {
                        product.setStock(product.getStock() + item.getQuantity());
                        product.setSales(product.getSales() - item.getQuantity());
                        productMapper.updateById(product);
                        log.info("恢复商品库存：productId={}, quantity={}", 
                                item.getProductId(), item.getQuantity());
                    }
                }
            }
            
            log.info("商家拒单成功：orderId={}, status=8", orderId);
            
        } catch (Exception e) {
            log.error("商家拒单退款失败：orderId={}", orderId, e);
            throw new BusinessException("退款失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void finishOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (order.getStatus() != OrderStatus.DELIVERING) {
            throw new BusinessException("订单状态错误，无法完成订单");
        }
        
        // 更新订单状态为已完成（统一状态v2.0：商家完成配送后状态为6）
        order.setStatus(6);
        order.setConfirmTime(LocalDateTime.now());
        order.setFinishTime(LocalDateTime.now());
        orderMapper.updateById(order);
        messageService.create(order.getUserId(), 1, "订单已完成", "订单" + order.getOrderNo() + "已完成", "order", order.getId());
    }

    @Override
    public void updateById(Order order) {
        orderMapper.updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlePaySuccess(String orderNo, String transactionId) {
        // 查询订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo, orderNo);
        Order order = orderMapper.selectOne(wrapper);
        
        if (order == null) {
            throw new BusinessException("订单不存在：" + orderNo);
        }
        
        // 如果订单已支付，直接返回（防止重复处理）
        if (order.getStatus() > 0) {
            log.warn("订单已支付，无需重复处理：orderNo={}, currentStatus={}", orderNo, order.getStatus());
            return;
        }
        
        log.info("处理支付成功：orderNo={}, transactionId={}, orderType={}", 
                orderNo, transactionId, order.getOrderType());
        
        // 更新订单状态
        order.setTransactionId(transactionId);
        order.setPayType(2); // 微信支付
        order.setPayTime(LocalDateTime.now());
        order.setStatus(1); // 待接单
        
        orderMapper.updateById(order);
        messageService.create(order.getUserId(), 1, "订单支付成功", "订单" + order.getOrderNo() + "已支付，等待商家接单", "order", order.getId());
        
        // 判断订单类型，处理不同业务逻辑
        Integer orderType = order.getOrderType();
        
        // orderType: 1-零食订单, 2-取快递, 3-取外卖, 4-代取奶咖, 5-其他服务
        if (orderType != null && orderType == 1) {
            // 零食订单：扣减库存
            handleSnackOrderPay(order.getId());
            log.info("零食订单库存已扣减：orderNo={}", orderNo);
            
            // 为商家创建消息：新订单提醒（仅零食订单）
            try {
                Long merchantId = getMerchantId();
                if (merchantId != null) {
                    merchantMessageService.create(merchantId, 1, "新订单提醒", "收到新订单：" + order.getOrderNo() + "，金额¥" + order.getActualAmount(), "order", order.getId());
                }
            } catch (Exception e) {
                log.warn("创建商家消息失败, orderId={}", order.getId(), e);
            }
        } else if (orderType != null && (orderType == 2 || orderType == 3 || orderType == 4 || orderType == 5)) {
            // 代取订单：确认图片
            handleErrandOrderPay(order.getId());
            log.info("代取订单图片已确认：orderNo={}", orderNo);
            // 代取订单不需要在支付时创建商家消息，只在退款时创建
        }
        
        log.info("订单支付成功处理完成：orderNo={}, newStatus={}", orderNo, order.getStatus());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleRefund(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        log.info("处理退款：orderId={}, orderNo={}, status={}", 
                orderId, order.getOrderNo(), order.getStatus());
        
        // 更新订单状态为已退款
        order.setStatus(8);
        orderMapper.updateById(order);
        messageService.create(order.getUserId(), 1, "订单已退款", "订单" + order.getOrderNo() + "已退款", "order", order.getId());
        
        // 如果是零食订单，恢复商品库存
        if (order.getOrderType() == 1) {
            LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderItem::getOrderId, orderId);
            List<OrderItem> items = orderItemMapper.selectList(wrapper);
            
            for (OrderItem item : items) {
                Product product = productMapper.selectById(item.getProductId());
                if (product != null) {
                    product.setStock(product.getStock() + item.getQuantity());
                    productMapper.updateById(product);
                    log.info("恢复商品库存：productId={}, quantity={}, newStock={}", 
                            item.getProductId(), item.getQuantity(), product.getStock());
                }
            }
        }
        
        log.info("订单退款处理完成：orderId={}, orderNo={}", orderId, order.getOrderNo());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int autoCancelUnpaidOrders(LocalDateTime deadline) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getStatus, OrderStatus.WAIT_PAY)
               .lt(Order::getCreateTime, deadline);
        List<Order> expiredOrders = orderMapper.selectList(wrapper);
        if (expiredOrders == null || expiredOrders.isEmpty()) {
            return 0;
        }

        LocalDateTime now = LocalDateTime.now();
        int count = 0;
        for (Order order : expiredOrders) {
            order.setStatus(OrderStatus.CANCELLED);
            order.setCancelReason("超过15分钟未支付，系统自动取消");
            order.setCancelTime(now);
            orderMapper.updateById(order);
            count++;

            try {
                messageService.create(
                    order.getUserId(),
                    1,
                    "订单支付超时已取消",
                    "订单" + order.getOrderNo() + "超过15分钟未支付，系统已自动取消",
                    "order",
                    order.getId()
                );
            } catch (Exception e) {
                log.warn("创建订单超时取消通知失败，orderId={}", order.getId(), e);
            }
        }
        log.info("自动取消超时未支付订单完成，数量={}, deadline={}", count, deadline);
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrderByMerchant(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        orderMapper.deleteById(orderId);
        log.info("商家删除订单成功：orderId={}", orderId);
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.format("%04d", new Random().nextInt(10000));
        return "SN" + timestamp + random;
    }

    /**
     * 构建地址文本
     */
    private String buildAddressText(Address address) {
        return String.format("%s %s %s %s",
            address.getBuilding(),
            address.getRoom(),
            address.getContactName(),
            address.getContactPhone()
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applyRefund(Long userId, Long orderId, String reason) {
        // 1. 校验订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权限操作此订单");
        }

        // 2. 校验订单状态是否允许退款
        if (!canRefund(order)) {
            throw new BusinessException("当前订单状态不允许退款");
        }

        // 3. 校验是否已经在退款流程中
        if (order.getRefundStatus() != null && order.getRefundStatus() > 0) {
            throw new BusinessException("订单已在退款流程中");
        }

        // 4. 根据订单状态判断退款方式
        if (order.getStatus() == 0) {
            // 待支付状态：直接取消，无需退款
            order.setStatus(OrderStatus.CANCELLED); // 已取消
            order.setCancelReason(reason);
            order.setCancelTime(LocalDateTime.now());
            orderMapper.updateById(order);
            return false; // 无需审核
        } else if (order.getStatus() == 1) {
            // 待接单状态：自动全额退款
            processAutoRefund(order, reason);
            return false; // 无需审核
        } else if (order.getStatus() == 3 || order.getStatus() == 2) {
            // 配送中或待取件状态：需要商家审核
            applyRefundWithApproval(order, reason);
            return true; // 需要审核
        } else {
            throw new BusinessException("当前订单状态不允许退款");
        }
    }

    @Override
    public Order getRefundStatus(Long orderId) {
        return orderMapper.selectById(orderId);
    }

    /**
     * 判断订单是否可以退款
     */
    private boolean canRefund(Order order) {
        // 待支付、待接单、配送中、待取件状态可以退款
        return order.getStatus() == 0 || order.getStatus() == 1 || 
               order.getStatus() == 2 || order.getStatus() == 3;
    }

    /**
     * 自动退款处理（待接单状态）
     */
    private void processAutoRefund(Order order, String reason) {
        try {
            // 1. 调用微信退款
            String refundNo = wxPayService.refund(order, reason);
            log.info("订单{}自动退款成功，退款单号：{}", order.getOrderNo(), refundNo);

            // 2. 更新订单状态
            order.setStatus(8); // 已退款
            order.setRefundStatus(2); // 退款成功
            order.setRefundAmount(order.getActualAmount());
            order.setRefundApplyTime(LocalDateTime.now());
            order.setCancelReason(reason);
            order.setCancelTime(LocalDateTime.now());

            // 3. 恢复库存（零食订单）
            if (order.getOrderType() == 1) {
                restoreStock(order.getId());
            }

            orderMapper.updateById(order);
            messageService.create(order.getUserId(), 1, "订单已退款", "订单" + order.getOrderNo() + "已退款", "order", order.getId());
            
            // 4. 为商家创建消息：退款已处理（自动退款）
            try {
                Long merchantId = getMerchantId();
                if (merchantId != null) {
                    merchantMessageService.create(merchantId, 2, "退款已处理", "订单" + order.getOrderNo() + "退款已处理，退款金额¥" + order.getActualAmount(), "order", order.getId());
                }
            } catch (Exception e) {
                log.warn("创建商家消息失败, orderId={}", order.getId(), e);
            }
            
        } catch (Exception e) {
            log.error("订单{}自动退款失败", order.getOrderNo(), e);
            throw new BusinessException("退款失败，请稍后重试");
        }
    }

    /**
     * 提交退款审核（配送中状态）
     */
    private void applyRefundWithApproval(Order order, String reason) {
        // 1. 更新订单状态为退款审核中
        order.setStatus(9); // 退款审核中
        order.setRefundStatus(1); // 退款审核中
        order.setRefundApplyTime(LocalDateTime.now());
        order.setCancelReason(reason);
        
        orderMapper.updateById(order);
        messageService.create(order.getUserId(), 1, "退款申请已提交", "订单" + order.getOrderNo() + "退款申请已提交，等待审核", "order", order.getId());
        log.info("订单{}提交退款审核，等待商家处理", order.getOrderNo());
    }

    /**
     * 恢复库存（零食订单）
     */
    private void restoreStock(Long orderId) {
        // 查询订单明细
        LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(wrapper);
        
        // 恢复每个商品的库存和销量
        for (OrderItem item : orderItems) {
            Product product = productMapper.selectById(item.getProductId());
            if (product != null) {
                // 恢复库存
                product.setStock(product.getStock() + item.getQuantity());
                // 减少销量
                if (product.getSales() != null && product.getSales() >= item.getQuantity()) {
                    product.setSales(product.getSales() - item.getQuantity());
                }
                productMapper.updateById(product);
            }
        }
    }

    @Override
    public List<ReorderItemDTO> getReorderItems(Long userId, Long orderId) {
        // 1. 校验订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权限操作此订单");
        }
        if (order.getOrderType() == null || order.getOrderType() != 1) {
            throw new BusinessException("仅零食订单支持再来一单");
        }

        // 2. 查询订单明细
        LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItems = orderItemMapper.selectList(wrapper);

        // 3. 组装复购清单（过滤已下架或无库存，数量限制在库存内且至少为1）
        List<ReorderItemDTO> result = new ArrayList<>();
        for (OrderItem item : orderItems) {
            Product product = productMapper.selectById(item.getProductId());
            if (product == null) {
                continue;
            }
            // 状态：1-上架
            if (product.getStatus() == null || product.getStatus() != 1) {
                continue;
            }
            // 库存需要大于0
            Integer stock = product.getStock();
            if (stock == null || stock <= 0) {
                continue;
            }

            int originQty = item.getQuantity() != null ? item.getQuantity() : 1;
            int qty = Math.max(1, Math.min(originQty, stock));

            ReorderItemDTO dto = new ReorderItemDTO();
            dto.setProductId(product.getId());
            dto.setName(product.getName() != null ? product.getName() : item.getProductName());
            dto.setImage(product.getImage() != null ? product.getImage() : item.getProductImage());
            dto.setPrice(product.getPrice() != null ? product.getPrice() : item.getPrice());
            dto.setQuantity(qty);
            result.add(dto);
        }

        if (result.isEmpty()) {
            throw new BusinessException("商品均已下架或无库存，无法再来一单");
        }

        return result;
    }

    /**
     * 获取商家ID（单商户模式：查询 user_type=3 的用户）
     */
    private Long getMerchantId() {
        try {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserType, 3) // user_type=3 为商家
                   .last("limit 1");
            User merchant = userMapper.selectOne(wrapper);
            return merchant != null ? merchant.getId() : null;
        } catch (Exception e) {
            log.error("获取商家ID失败", e);
            return null;
        }
    }
}

